﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yoze.Common;
using Yoze.Common.Messaging;

using Yoze.Redis.Common;

namespace Yoze.Messaging.RedisMq
{
    /// <summary>
    /// 消息订阅者
    /// </summary>
    public class RedisMqMessageSubscriber : DisposableObject, IMessageSubscriber
    {
        private readonly string exchangeName;
        private readonly string queueName;
        private readonly string url;
        private bool disposed;
        private RedisService redis;

        public event EventHandler<MessageReceivedEventArgs> MessageReceived;

        /// <summary>
        /// Initializes a new instance of <c>RedisMqMessageSubscriber</c> class.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="exchangeName"></param>
        /// <param name="queueName"></param>
        public RedisMqMessageSubscriber(string uri, string exchangeName, string queueName)
        {
            this.exchangeName = exchangeName;
            this.queueName = queueName;
            this.url = uri;
            redis = new RedisService(uri);
        }

        /// <summary>
        /// 订阅/处理消息客户端
        /// </summary>
        public void Subscribe()
        {
            redis.Subscription(exchangeName, (a, b) =>
            {
                var message = JsonConvert.DeserializeObject(b, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
                this.OnMessageReceived(new MessageReceivedEventArgs(message));
            }).Start();

            System.Diagnostics.Trace.WriteLine($"RedisMq subscription client:{exchangeName}");
        }

        private void OnMessageReceived(MessageReceivedEventArgs e)
        {
            this.MessageReceived?.Invoke(this, e);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!disposed)
                {
                    disposed = true;
                }
            }
        }
    }
}
